package com.itheima.reggie.controller;

import com.itheima.reggie.service.EmployeeService;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpSession session;


    /*登录*/
    @PostMapping("/employee/login")
    public ResultInfo login(@RequestBody Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        /*调用service层登录*/
        ResultInfo resultInfo = employeeService.login(username, password);
        /*获取返回值中的数据，存入session*/
        Employee employee = (Employee) resultInfo.getData();
        session.setAttribute("SESSION_EMPLOYEE", employee);
        return resultInfo;
    }


    /*退出*/
    @PostMapping("/employee/logout")
    public ResultInfo logout() {

        /*清除session里面的登录信息*/
//        session.removeAttribute("SESSION_EMPLOYEE");

        /*注销当前的用户session*/
        session.invalidate();
        return ResultInfo.success(null);
    }

    /*员工列表*/
    @GetMapping("/employee/find")
    public ResultInfo find(String name) {
        List<Employee> list = employeeService.findByName(name);
        return ResultInfo.success(list);
    }


    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        employeeService.save(employee);
        return ResultInfo.success(null);
    }

    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Employee employee = employeeService.findById(id);
        return ResultInfo.success(employee);
    }

    @PutMapping("/employee")
    public ResultInfo update(@RequestBody Employee employee){
        employeeService.update(employee);
        return ResultInfo.success(null);
    }
}
